<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>供应商管理</template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="openAddModal">
            <template #icon><icon-plus /></template>
            新增供应商
          </a-button>
          <a-button @click="handleImport">
            <template #icon><icon-import /></template>
            批量导入
          </a-button>
          <a-button @click="handleExport">
            <template #icon><icon-export /></template>
            导出数据
          </a-button>
        </a-space>
      </template>
      
      <!-- 搜索区域 -->
      <a-form :model="searchForm" class="search-form" layout="inline">
        <a-form-item field="code" label="供应商编码">
          <a-input
            v-model="searchForm.code"
            placeholder="请输入供应商编码"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="name" label="供应商名称">
          <a-input
            v-model="searchForm.name"
            placeholder="请输入供应商名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            allow-clear
          >
            <a-option :value="1">启用</a-option>
            <a-option :value="0">禁用</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 表格区域 -->
      <a-table
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
        stripe
      >
        <template #columns>
          <a-table-column title="供应商编码" data-index="code" :width="120" />
          <a-table-column title="供应商名称" data-index="name" :width="200" />
          <a-table-column title="联系人" data-index="contact" :width="100" />
          <a-table-column title="联系电话" data-index="phone" :width="120" />
          <a-table-column title="地址" data-index="address" :width="200" :ellipsis="true" tooltip />
          <a-table-column title="状态" data-index="status" :width="80">
            <template #cell="{ record }">
              <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '禁用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="180">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-divider direction="vertical" />
                <a-button 
                  type="text" 
                  size="small" 
                  @click="handleToggleStatus(record)"
                >
                  {{ record.status === 1 ? '禁用' : '启用' }}
                </a-button>
                <a-divider direction="vertical" />
                <a-popconfirm
                  content="确定要删除这个供应商吗？"
                  @ok="handleDelete(record.id)"
                >
                  <a-button type="text" status="danger" size="small">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑供应商弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="isEdit ? '编辑供应商' : '新增供应商'"
      @ok="handleSubmit"
      @cancel="closeModal"
      :mask-closable="false"
      :width="800"
      :footer="false"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="code" label="供应商编码" required>
              <a-input
                v-model="formData.code"
                placeholder="请输入供应商编码"
                :disabled="isEdit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="name" label="供应商名称" required>
              <a-input
                v-model="formData.name"
                placeholder="请输入供应商名称"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="contact" label="联系人" required>
              <a-input
                v-model="formData.contact"
                placeholder="请输入联系人姓名"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="phone" label="联系电话" required>
              <a-input
                v-model="formData.phone"
                placeholder="请输入联系电话"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="email" label="电子邮箱">
              <a-input
                v-model="formData.email"
                placeholder="请输入电子邮箱"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="status" label="状态" required>
              <a-radio-group v-model="formData.status" type="button">
                <a-radio :value="1">启用</a-radio>
                <a-radio :value="2">禁用</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="address" label="地址">
          <a-input
            v-model="formData.address"
            placeholder="请输入地址"
          />
        </a-form-item>
        <!-- Removed TaxNumber, Bank, Account, Remark fields -->
        <!-- <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="tax_number" label="税号">
              <a-input
                v-model="formData.tax_number"
                placeholder="请输入税号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="bank" label="开户行">
              <a-input
                v-model="formData.bank"
                placeholder="请输入开户行"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="account" label="银行账号">
          <a-input
            v-model="formData.account"
            placeholder="请输入银行账号"
          />
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea
            v-model="formData.remark"
            placeholder="请输入备注"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item> -->
        <div class="modal-footer">
          <a-space>
            <a-button @click="closeModal">取消</a-button>
            <a-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>

    <!-- 批量导入供应商弹窗 -->
    <a-modal
      v-model:visible="importVisible"
      title="批量导入供应商"
      @ok="handleImportSubmit"
      @cancel="importVisible = false"
      :mask-closable="false"
    >
      <a-upload
        :custom-request="customRequest"
        :show-file-list="false"
        accept=".xlsx,.xls"
      >
        <template #upload-button>
          <a-button type="primary">
            <template #icon><icon-upload /></template>
            选择文件
          </a-button>
        </template>
      </a-upload>
      <div class="upload-tip">
        <p>支持 .xlsx、.xls 格式的文件</p>
        <a-link @click="downloadTemplate">下载导入模板</a-link>
      </div>
    </a-modal>
  </div>
</template>

<script>
export default {
  name: 'SupplierProfile'
}
</script>

<script setup>
import { ref, reactive, onMounted, markRaw, computed } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { 
  IconPlus, 
  IconEdit, 
  IconDelete, 
  IconImport, 
  IconExport,
  IconUpload,
  IconSearch,
  IconRefresh
} from '@arco-design/web-vue/es/icon';
import { useSupplierStore } from '@/stores/supplier';

// 使用markRaw包装图标组件
const icons = {
  plus: markRaw(IconPlus),
  edit: markRaw(IconEdit),
  delete: markRaw(IconDelete),
  import: markRaw(IconImport),
  export: markRaw(IconExport),
  upload: markRaw(IconUpload),
  search: markRaw(IconSearch),
  refresh: markRaw(IconRefresh)
};

// 使用store
const supplierStore = useSupplierStore();

// 表格数据和加载状态
const tableData = computed(() => supplierStore.suppliers);
const loading = computed(() => supplierStore.loading);
const pagination = computed(() => supplierStore.pagination);

// 搜索表单
const searchForm = reactive({
  code: '',
  name: '',
  status: undefined
});

// 供应商类型选项
const supplierTypes = ref([
  { label: '生产商', value: 'manufacturer' },
  { label: '代理商', value: 'agent' },
  { label: '分销商', value: 'distributor' },
  { label: '服务商', value: 'service' }
]);

// 弹窗控制
const modalVisible = ref(false);
const importVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const submitLoading = ref(false);
const formData = reactive({
  code: '',
  name: '',
  contact: '',
  phone: '',
  email: '',
  address: '',
  status: 1,
  tax_number: '',
  bank: '',
  account: '',
  remark: ''
});

// 表单验证规则
const formRules = {
  code: [
    { required: true, message: '请输入供应商编码' },
    { match: /^[A-Za-z0-9-]+$/, message: '供应商编码只能包含字母、数字和连字符' }
  ],
  name: [
    { required: true, message: '请输入供应商名称' },
    { maxLength: 50, message: '供应商名称最多50个字符' }
  ],
  contact: [
    { required: true, message: '请输入联系人姓名' }
  ],
  phone: [
    { required: true, message: '请输入联系人电话' },
    { match: /^1[3-9]\d{9}$/, message: '联系电话格式不正确' }
  ],
  status: [
    { required: true, message: '请选择状态' }
  ]
};

// 获取类型名称
const getTypeName = (type) => {
  const found = supplierTypes.value.find(item => item.value === type);
  return found ? found.label : '未知类型';
};

// 搜索方法
const handleSearch = () => {
  // 构建查询参数
  const params = {};
  if (searchForm.code) params.code = searchForm.code;
  if (searchForm.name) params.name = searchForm.name;
  if (searchForm.status !== undefined) params.status = searchForm.status;
  
  // 重置页码并获取数据
  supplierStore.setPagination(1, pagination.value.pageSize);
  fetchSupplierList(params);
};

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'status' ? undefined : '';
  });
  supplierStore.setPagination(1, pagination.value.pageSize);
  fetchSupplierList();
};

// 获取供应商列表
const fetchSupplierList = async (params = {}) => {
  try {
    const result = await supplierStore.getSupplierList(params);
    console.log('fetchSupplierList返回结果:', result);
    return result; // 返回结果以便在其他地方使用
  } catch (error) {
    console.error('调用getSupplierList出错:', error);
    return { success: false, message: error.message || '获取供应商列表失败' };
  }
};

// 分页变化
const onPageChange = (page) => {
  supplierStore.setPagination(page, pagination.value.pageSize);
  fetchSupplierList();
};

// 每页数量变化
const onPageSizeChange = (pageSize) => {
  supplierStore.setPagination(1, pageSize);
  fetchSupplierList();
};

// 打开新增弹窗
const openAddModal = () => {
  isEdit.value = false;
  Object.assign(formData, {
    code: '',
    name: '',
    contact: '',
    phone: '',
    email: '',
    address: '',
    status: 1,
    tax_number: '',
    bank: '',
    account: '',
    remark: ''
  });
  modalVisible.value = true;
};

// 处理编辑
const handleEdit = (record) => {
  isEdit.value = true;
  Object.assign(formData, JSON.parse(JSON.stringify(record)));
  modalVisible.value = true;
};

// 处理提交
const handleSubmit = async () => {
  // 表单验证
  const valid = await formRef.value.validate();
  
  if (!valid) return;
  
  submitLoading.value = true;
  try {
    const data = { ...formData };
    // 处理表单数据
    
    let result;
    if (isEdit.value) {
      result = await supplierStore.updateSupplier(data.id, data);
    } else {
      result = await supplierStore.createSupplier(data);
    }
    
    if (result.success) {
      modalVisible.value = false;
      fetchSupplierList();
    }
  } finally {
    submitLoading.value = false;
  }
};

// 关闭弹窗
const closeModal = () => {
  formRef.value?.resetFields();
  modalVisible.value = false;
};

// 处理状态切换
const handleToggleStatus = (record) => {
  // TODO: 调用状态切换接口
  const newStatus = record.status === 1 ? 2 : 1;
  const actionText = newStatus === 1 ? '启用' : '禁用';
  
  // 模拟API请求
  setTimeout(() => {
    const index = tableData.value.findIndex(item => item.id === record.id);
    if (index !== -1) {
      tableData.value[index].status = newStatus;
      Message.success(`${actionText}成功`);
    }
  }, 500);
};

// 处理删除
const handleDelete = async (id) => {
  const result = await supplierStore.deleteSupplier(id);
  if (result.success) {
    fetchSupplierList();
  }
};

// 处理导入
const handleImport = () => {
  importVisible.value = true;
};

// 处理导出
const handleExport = () => {
  // TODO: 调用导出接口
  Message.success('导出成功');
};

// 自定义上传请求
const customRequest = (options) => {
  const { file } = options;
  // TODO: 处理文件上传
  console.log('上传文件：', file);
};

// 下载模板
const downloadTemplate = () => {
  // TODO: 下载导入模板
};

// 处理导入提交
const handleImportSubmit = () => {
  // TODO: 处理文件导入
  importVisible.value = false;
  Message.success('导入成功');
  fetchSupplierList();
};

// 初始化
onMounted(() => {
  console.log('供应商管理页面已加载');
  fetchSupplierList().then((result) => {
    console.log('获取供应商数据完成，当前数据:', tableData.value);
    // 判断是否获取数据成功
    if (result && result.success && tableData.value.length > 0) {
      console.log('成功从API获取供应商数据');
      Message.success('获取供应商信息成功');
    } 
    // 仅在开发环境并且没有获取到数据时使用测试数据
    else if (process.env.NODE_ENV !== 'production' && tableData.value.length === 0) {
      console.warn('供应商数据为空，设置本地测试数据');
      // 通过store设置suppliers而不是直接修改tableData
      supplierStore.suppliers = [
        {
          id: 1,
          code: 'SUP001',
          name: '北极冷链物流有限公司',
          contact: '张三',
          phone: '13800138001',
          email: 'zhangsan@beiji.com',
          status: 1,
          address: '北京市朝阳区建国路88号',
          remark: '专业冷链物流供应商',
          tax_number: '91110000XXXXXXXXXX',
          bank: '中国工商银行北京顺义支行',
          account: '6212260200012345678'
        },
        {
          id: 2,
          code: 'SUP002',
          name: '雪域冷冻食品有限公司',
          contact: '李四',
          phone: '13900139001',
          email: 'lisi@xueyu.com',
          status: 1,
          address: '上海市浦东新区张江高科技园区',
          remark: '专营冷冻肉类批发',
          tax_number: '91210000XXXXXXXXXX',
          bank: '中国建设银行上海分行',
          account: '6227001215632145698'
        },
        {
          id: 3,
          code: 'SUP003',
          name: '海洋冷冻食品有限公司',
          contact: '王五',
          phone: '13700137001',
          email: 'wangwu@haiyang.com',
          status: 1,
          address: '广州市黄埔区科学城',
          remark: '海鲜冷冻食品专业供应商',
          tax_number: '91440000XXXXXXXXXX',
          bank: '中国银行广州分行',
          account: '6216610100001234567'
        }
      ];
    }
  });
});
</script>

<style lang="less" scoped>
@import '@/styles/variables.less';

.container {
  padding: 0 20px 20px 20px;
}

.general-card {
  margin-top: 16px;
  margin-bottom: 20px;
  
  :deep(.arco-card-header) {
    height: 52px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border);
  }
}

.search-form {
  margin-bottom: 8px;
}

.contact-list {
  .contact-item {
    margin-bottom: 16px;
    padding: 16px;
    background-color: var(--color-bg-2);
    border-radius: 4px;
    
    .contact-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      h4 {
        margin: 0;
        font-size: 15px;
        color: var(--color-text-1);
      }
    }
  }
  
  .add-contact {
    margin-top: 16px;
  }
}

.upload-tip {
  margin-top: 16px;
  
  p {
    margin-bottom: 8px;
    color: var(--color-text-3);
  }
}

.modal-footer {
  margin-top: 24px;
  text-align: right;
  border-top: 1px solid var(--color-neutral-3);
  padding-top: 16px;
}

:deep(.arco-tabs-content) {
  min-height: 300px;
}

:deep(.arco-radio-group) {
  flex-wrap: wrap;
}

:deep(.arco-form) {
  .arco-form-item-label {
    font-weight: 500;
  }
  
  .arco-input, 
  .arco-select, 
  .arco-textarea {
    width: 100%;
  }
}

:deep(.arco-modal-body) {
  max-height: 70vh;
  overflow-y: auto;
}

@media screen and (max-width: 768px) {
  :deep(.arco-row) {
    margin-right: 0 !important;
    margin-left: 0 !important;
  }
  
  :deep(.arco-col) {
    padding-right: 0 !important;
    padding-left: 0 !important;
  }
}

:deep(.arco-modal-footer .arco-btn),
:deep(.modal-footer .arco-btn) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style> 